<?php

/**
 * @Author: king
 * @Date:   2019-05-04 19:18:14
 * @Last Modified by:   king
 * @Last Modified time: 2019-06-04 23:27:34
 */
namespace App\Models\Api;
use App\Exceptions\ApiException;
use App\Models\Api\Base;
use Cache;

class LanmeiUserAccount extends Base
{
    protected $table = 'user_account';

     public $timestamps = false;
    /**
     * 获取账户信息
     * @param $uid
     * @return array|object
     * @throws ApiException
     */
    public function getAccountInfoAndCreate($uid)
    {
        try
        {
            $accountInfoModel = $this->where('uid', $uid)
            ->select('total_amount','withdraw_price','balance','status','uid','last_time')
            ->orderBy('id', 'DESC')
            ->first();

            // 判断用户账户是否存在或开通
            if ($accountInfoModel == null || empty($accountInfoModel))
            {
                // 初始化账户
                $accountInfo = $this->createAccount($uid);
            } else
            {
                $accountInfo = $accountInfoModel->toArray();
            }
        }
        catch (Exception $e)
        {
            throw new ApiException('服务异常', 200, config('code.error'));
        }

        return $accountInfo;
    }

    /**
     * 账户初始化创建
     * @param $uid
     * @return array
     * @throws Exception
     */
    protected function createAccount($uid)
    {
        $data = [
            'uid' => $uid,
            'status' => 1,
            'last_time' => 0,
            'withdraw_price' => '0.00',
            'balance' => '0.00',
            'total_amount' => '0.00',
            'create_time' => time()
        ];

        try
        {
            $id = $this->insertGetId($data);

            $data['id'] = $this->id;
        }
        catch (\Exception $e)
        {
            throw new ApiException('服务异常', 200, config('code.error'));
        }

        return $data;
    }

    /**
     * 咨询师账户变更 --> 获取问答赏金
     * @param $counselorPrice
     * @param $gid
     * @param $time
     * @throws \Exception
     */
    public function counselorAccountAdd($counselorPrice, $gid, $time)
    {
        $cIds = array_keys($counselorPrice);
        // 获取咨询师信息
        $counInfo = (new LanmeiCounselor())->batchGetInfoByIds($cIds, ['uid']); // 咨询师信息

        $userPrice = [];
        $uids = [];
        foreach ($counselorPrice as $cId => $price)
        {
            $userPrice[$counInfo[$cId]['uid']] = $price;    // 重组数据结构
            array_push($uids, $counInfo[$cId]['uid']);// 获取用户ID

            $data = [
                'total_amount' => $this->raw('total_amount+' . $price),
                'balance' => $this->raw('balance+' . $price),
            ];
            $this->where(['uid' => $counInfo[$cId]['uid']])->update($data); // 账户金额递增
        }

        // 获取用户账户最新的信息
        $accountInfos = $this->whereIn('uid', $uids)->get(['id','uid','total_amount','balance'])->keyBy('id')->toArray();

        $recordData = [];
        foreach ($accountInfos as $accountInfoItem)
        {
            // 组合 账户流水
            $recordData[] = [
                'create_time' => $time,
                'record_type' => 1,
                'gid' => $gid,
                'price' => $userPrice[$accountInfoItem['uid']],
                'balance' => $accountInfoItem['balance'],
                'account_id' => $accountInfoItem['id'],
                'extend' => ''
            ];
        }
        // 批量写入 账户流水
        (new LanmeiUserAccountRecord())->create($recordData);
    }
}
